package com.shoping.common.queue.producer;

import lombok.extern.slf4j.Slf4j;

import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * TODO
 *
 * @author zengweilong
 * @date 4/14/21 6:37 PM
 */
@Slf4j
public class Producer implements Runnable {

    private BlockingQueue queue;

    private volatile boolean isRunning = true;

    private static AtomicInteger count = new AtomicInteger();

    private static final int DEFAULT_RANGE_FOR_SLEEP = 1000;

    public Producer(BlockingQueue queue) {
        this.queue = queue;
    }

    @Override
    public void run() {

        String data = null;
        log.info("启动生产者线程！");
        Random random = new Random();
        try {
            while (isRunning) {
                log.info("正在生产数据...");
                Thread.sleep(random.nextInt(DEFAULT_RANGE_FOR_SLEEP));
                data = "data:" + count.incrementAndGet();
                log.info("将队列" + data + "放入队列...");
                if (!queue.offer(data, 2, TimeUnit.SECONDS)) {
                    log.info("放入数据失败:" + data);

                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            Thread.currentThread().interrupt();
        } finally {
            log.info("退出生产者线程！");
        }


    }

    public void stop() {
        isRunning = false;
    }
}
